import com.opdar.athena.base.Message;
import com.opdar.athena.base.MessageType;
import com.opdar.athena.entities.MessageEntity;
import com.opdar.athena.entities.UserMigrateEntity;
import com.opdar.athena.messages.HeartbeatMessage;
import com.opdar.athena.messages.MigrateMessage;
import com.opdar.athena.utils.JSONUtil;
import com.sun.tools.javac.util.Names;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;

/**
 * Created by shiju on 2017/7/4.
 */
public class ReadRunnable extends DataInputStream implements Runnable {
    private Socket socket;
    private byte[] project;
    private boolean isStop = false;
    private MessageCallback messageCallback;

    public ReadRunnable(Socket socket, byte[] project, MessageCallback messageCallback) throws IOException {
        super(socket.getInputStream());
        this.socket = socket;
        this.project = project;
        this.messageCallback = messageCallback;
    }

    public void stop() {
        isStop = true;
    }

    @Override
    public void run() {
            while (!isStop) {
                try {
                    byte[] _project = new byte[project.length];
                    read(_project);
                    int version = readInt();
                    int type = readShort();
                    int length = readInt();
                    byte[] body = new byte[length];
                    read(body);
                    switch (type) {
                        case MessageType.HEARTBEAT:
                            messageCallback.heartbeat(new HeartbeatMessage(body));
                            break;
                        case MessageType.MESSAGE:
                            messageCallback.callback(JSONUtil.parseObject(body, MessageEntity.class));
                            break;
                        case MessageType.MIGRATE:
                            messageCallback.migrate(JSONUtil.parseObject(body, UserMigrateEntity.class));
                            break;
                    }
                }catch (SocketException e){
                    stop();
                    messageCallback.onClose();
                    break;
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
    }
}
